from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthUser
from oauth.utils import check_save_user_token
from users.models import User


class QQAuthUserSerializer(serializers.Serializer):
    # write_only = True     限制当前字段只能是客户端提交
    access_token = serializers.CharField(write_only=True, help_text='jwt  token')
    # regex 选项，  表示让当前字段的值必须要符合正则要求
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length= 20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    def validate_access_token(self, value):
        # value 是加密后的access_token
        # 1. 校验access_token
        openid = check_save_user_token(value)
        print(openid)
        if openid is None:
            raise serializers.ValidationError({'message': 'openid获取失败'})
        return openid

    def validate(self, attrs):
        # print(attrs)
        # 2.校验短信验证码
        mobile = attrs['mobile']
        sms_code = attrs['sms_code']
        redis = get_redis_connection('verify')
        try:
            real_sms_code = redis.get('sms_%s' % mobile)
            real_sms_code = real_sms_code.decode()
        except Exception as e:
            raise serializers.ValidationError({'message': '短信验证码获取失败'})

        if sms_code != real_sms_code:
            raise serializers.ValidationError({'message': '短信验证码错误'})
        # 3. 判断账号是否存在
        try:
            user = User.objects.get(mobile=mobile)
            attrs['user'] = user
        except User.DoesNotExist:
            pass
        else:
            # 3.1 账号存在，则判断密码是否正确
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError({'message': '密码错误'})
            return attrs

    def create(self, validate_data):
        user = validate_data.get('user')
        if user is None:
            user = User.objects.create(
                username=validate_data['mobile'],
                mobile=validate_data['mobile'],
                password=validate_data['password'],
            )

            # 新增账号的密码要加密
            user.set_password(validate_data['password'])
            user.save()

        # 4. 把账号和QQ的openid绑定到新的表auth_qq中
        OAuthUser.objects.create(
            openid=validate_data['access_token'],
            user=user,
        )

        # 返回jwt到视图里
        return user
